package cn.group.controller;

import cn.group.service.ImgDoService;
import constants.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.entity.ImgDo;
import utils.BaseController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "图片操作")
@Controller
@RequestMapping(value = "/imgDo" , produces = "text/html;charset=UTF-8")
public class ImgDoController extends BaseController {

    @Autowired
    private ImgDoService imgDoService;

    @ApiOperation("上传图片")
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam MultipartFile[] imgs,String id,
                             HttpSession session) {
        //服务器根目录
        System.out.println("上传的到的文件夹"+id);
        String path = Constants.TP_IMG_PATH+id;
        //遍历图片数组
        for (MultipartFile img : imgs) {
            String fileName = img.getOriginalFilename();
            File file = new File(path, fileName);
            try {
                img.transferTo(file);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "welcome";
    }

    @ApiOperation("删除图片")
    @RequestMapping("/deleteImg")
    @ResponseBody
    public String deleteImg(@RequestParam(value = "fileNames[]") String[] fileNames) {
        for (int i = 0; i < fileNames.length; i++) {
            String fileName = "D:/log/"+fileNames[i];
            /*删除操作*/
            File file = new File(fileName);
            // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    System.out.println("删除单个文件" + fileName + "成功！");
                } else {
                    System.out.println("删除单个文件" + fileName + "失败！");
                }
            } else {
                System.out.println("删除单个文件失败：" + fileName + "不存在！");
            }
        }
        return "zzz";
    }

    @ApiOperation("下载默认图片")
    @RequestMapping("/fileMr")
    public ResponseEntity<byte[]> downloadMr(@RequestParam(name = "id") String id) throws Exception {

        String path=Constants.TP_IMG_PATH+id;
        File file = new File(path);
        System.out.println("文件夹绝对路径"+file.getAbsolutePath());

        File[] files = file.listFiles();
        File f=files[0];
        InputStream fs = new FileInputStream(f);
        // 创建字节数组,并且设置数组大小为预估文件字节大小
        byte[] body = new byte[fs.available()];
        // 将输出流缓存到数组中
        fs.read(body);
        // 获取下载显示得文件名,解决乱码问题
        String name = f.getName();
        String downloadFileName = new String(name.getBytes("utf-8"),
                "ISO-8859-1");
        // 设置HTTP响应头信息，并以附件形势下载
        HttpHeaders hh = new HttpHeaders();
        hh.add("Content-Disposition", "attachment;filename=" + downloadFileName);
        HttpStatus status = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(body, hh, status);
        fs.close();
        return entity;
    }

    @ApiOperation("下载图片")
    @RequestMapping("/fileDownload")
    public ResponseEntity<byte[]> download(@RequestParam(name = "id") String id) throws Exception {

        ArrayList<ResponseEntity<byte[]>> arrayList=new ArrayList<>();
        String path=Constants.TP_IMG_PATH+id;
        File f = new File(path);
        System.out.println("图片文件绝对路径"+f.getAbsolutePath());

        InputStream fs = new FileInputStream(f);
        // 创建字节数组,并且设置数组大小为预估文件字节大小
        byte[] body = new byte[fs.available()];
        // 将输出流缓存到数组中
        fs.read(body);
        // 获取下载显示得文件名,解决乱码问题
        String name = f.getName();
        String downloadFileName = new String(name.getBytes("utf-8"),
                "ISO-8859-1");
        // 设置HTTP响应头信息，并以附件形势下载
        HttpHeaders hh = new HttpHeaders();
        hh.add("Content-Disposition", "attachment;filename=" + downloadFileName);
        HttpStatus status = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<>(body, hh, status);
        fs.close();
        return entity;
    }

    @ApiOperation("查询图片名称")
    @RequestMapping("/allPath")
    @ResponseBody
    public String allPath(String path){
        List<String> list=new ArrayList<>();
        File file=new File(Constants.TP_IMG_PATH+path);
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()){
                String name = files[i].getName();
                list.add(path+"/"+name);
            }
        }
        String all = writerSuccessResult(list);
        return all;
    }

    @ApiOperation("查询文件夹")
    @RequestMapping("/allTable")
    @ResponseBody
    public String allTable(){
        List<ImgDo> list=imgDoService.findAllP();
        list.forEach(item->{
            File file=new File(Constants.TP_IMG_PATH+item.imgPath);
            //获取最后修改时间
            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(file.lastModified()));
            item.setTime(format);
        });
        String success = writerSuccessResult(list);
        return success;
    }
}
